package com.atguigu.controller;

import com.atguigu.bean.Department;
import com.atguigu.bean.Employee;
import com.atguigu.dao.DepartmentDao;
import com.atguigu.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collection;

/**
 * @author wk
 * @create 2021-06-13 22:35
 * /employee        get  查询所有员工
 * /employee/1      get  根据id查询所有员工
 * /employee        post  添加员工
 * /employee        put   更新
 * /employee/1      delete  删除
 *
 *
 *
 */
@Controller
public class EmployeeController {
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private EmployeeDao employeeDao;

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String getList(Model model){
        Collection<Employee> employeeCollection = employeeDao.getAll();
        model.addAttribute("employeeCollection",employeeCollection);
        return "list";
    }
    @RequestMapping(value = "/toAdd",method = RequestMethod.GET)
    public String toAdd(Model model){
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "add";
    }
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String addEmployee(Employee employee){
        employeeDao.saveOrUpdate(employee);
        return "redirect:/test";
    }
    @RequestMapping(value = "/toUpdate/{id}",method = RequestMethod.GET)
    public String toUpdate(Model model,@PathVariable("id")Integer id){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "update";
    }
    @RequestMapping(value = "/employee",method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeDao.saveOrUpdate(employee);
        return "redirect:/test";
    }
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/test";
    }

}
